package com.hh.service.service.impl.merchant;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.hh.common.exception.HhException;
import com.hh.common.model.merchant.MerchantAdmin;
import com.hh.common.model.merchant.MerchantRole;
import com.hh.common.request.PageParamRequest;
import com.hh.common.request.SystemAdminAddRequest;
import com.hh.common.request.SystemAdminRequest;
import com.hh.common.request.SystemAdminUpdateRequest;
import com.hh.common.response.SystemAdminResponse;
import com.hh.common.utils.HhUtil;
import com.hh.common.utils.SecurityUtil;
import com.hh.common.utils.ValidateFormUtil;
import com.hh.service.dao.merchant.MerchantAdminDao;
import com.hh.service.service.merchant.MerchantAdminService;
import com.hh.service.service.merchant.MerchantRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class MerchantAdminServiceImpl extends ServiceImpl<MerchantAdminDao, MerchantAdmin> implements MerchantAdminService {

    @Resource
    private MerchantAdminDao dao;

    @Autowired
    private MerchantRoleService merchantRoleService;

    @Override
    public MerchantAdmin selectUserByUserName(String username) {
        LambdaQueryWrapper<MerchantAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(MerchantAdmin::getAccount, username);
        lqw.eq(MerchantAdmin::getIsDel, false);
        return dao.selectOne(lqw);
    }

    @Override
    public Boolean saveAdmin(SystemAdminAddRequest systemAdminAddRequest) {
        MerchantAdmin user = SecurityUtil.getMerLoginUserVo().getUser();

        // 管理员名称唯一校验
        Integer result = checkAccount(systemAdminAddRequest.getAccount());
        if (result > 0) {
            throw new HhException("管理员已存在");
        }
        // 如果有手机号，校验手机号
        if (StrUtil.isNotBlank(systemAdminAddRequest.getPhone())) {
            ValidateFormUtil.isPhoneException(systemAdminAddRequest.getPhone());
        }

        List<Integer> roles = Stream.of(systemAdminAddRequest.getRoles().split(",")).map(Integer::valueOf).collect(Collectors.toList());

        List<MerchantRole> rolesList = merchantRoleService.getRolesListByIds(roles);
        boolean isSuperAdmin = false;
        for (MerchantRole merchantRole : rolesList) {
            if(merchantRole.getIsSuperAdmin()){
                isSuperAdmin = true;
                break;
            }
        }

        MerchantAdmin merchantAdmin = new MerchantAdmin();
        BeanUtils.copyProperties(systemAdminAddRequest, merchantAdmin);
        
        String pwd = HhUtil.encryptPassword(merchantAdmin.getPwd(), merchantAdmin.getAccount());
        merchantAdmin.setPwd(pwd);
        merchantAdmin.setMerId(user.getMerId());
        merchantAdmin.setIsSuperAdmin(isSuperAdmin);
        return save(merchantAdmin);
    }

    @Override
    public List<SystemAdminResponse> getList(SystemAdminRequest request, PageParamRequest pageParamRequest) {
        MerchantAdmin user = SecurityUtil.getMerLoginUserVo().getUser();

        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带SystemAdminRequest类的多条件查询
        LambdaQueryWrapper<MerchantAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MerchantAdmin::getMerId,user.getMerId());
        if (StrUtil.isNotBlank(request.getRoles())) {
            lambdaQueryWrapper.eq(MerchantAdmin::getRoles, request.getRoles());
        }
        if (ObjectUtil.isNotNull(request.getStatus())) {
            lambdaQueryWrapper.eq(MerchantAdmin::getStatus, request.getStatus());
        }
        if (StrUtil.isNotBlank(request.getRealName())) {
            lambdaQueryWrapper.and(i -> i.like(MerchantAdmin::getRealName, request.getRealName())
                    .or().like(MerchantAdmin::getAccount, request.getRealName()));
        }
        List<MerchantAdmin> merchantAdmins = dao.selectList(lambdaQueryWrapper);
        if (CollUtil.isEmpty(merchantAdmins)) {
            return CollUtil.newArrayList();
        }
        List<SystemAdminResponse> systemAdminResponses = new ArrayList<>();
        List<MerchantRole> roleList = merchantRoleService.getAllList();
        for (MerchantAdmin admin : merchantAdmins) {
            SystemAdminResponse sar = new SystemAdminResponse();
            BeanUtils.copyProperties(admin, sar);
            sar.setLastTime(admin.getUpdateTime());
            if (StrUtil.isBlank(admin.getRoles())) {
                continue;
            }
            List<Integer> roleIds = HhUtil.stringToArrayInt(admin.getRoles());
            List<String> roleNames = new ArrayList<>();
            for (Integer roleId : roleIds) {
                List<MerchantRole> hasRoles = roleList.stream().filter(e -> e.getId().equals(roleId)).collect(Collectors.toList());
                if (hasRoles.size()> 0) {
                    roleNames.add(hasRoles.stream().map(MerchantRole::getRoleName).collect(Collectors.joining(",")));
                }
            }
            sar.setRoleNames(StringUtils.join(roleNames,","));
            systemAdminResponses.add(sar);
        }
        return systemAdminResponses;
    }

    @Override
    public Boolean updateAdmin(SystemAdminUpdateRequest systemAdminRequest) {
        MerchantAdmin user = SecurityUtil.getMerLoginUserVo().getUser();

        MerchantAdmin detail = getDetail(systemAdminRequest.getId());

        verifyAccount(systemAdminRequest.getId(), systemAdminRequest.getAccount());
        // 如果有手机号，校验手机号
        if (StrUtil.isNotBlank(systemAdminRequest.getPhone())) {
            ValidateFormUtil.isPhoneException(systemAdminRequest.getPhone());
        }
        if(!detail.getMerId().equals(user.getMerId())){
            throw new HhException("商户异常，修改失败");
        }
        MerchantAdmin merchantAdmin = new MerchantAdmin();
        BeanUtils.copyProperties(systemAdminRequest, merchantAdmin);
        merchantAdmin.setPwd(null);
        if (StrUtil.isNotBlank(systemAdminRequest.getPwd())) {
            String pwd = HhUtil.encryptPassword(systemAdminRequest.getPwd(), systemAdminRequest.getAccount());
            merchantAdmin.setPwd(pwd);
        }
        return updateById(merchantAdmin);
    }

    /**
     * 管理员详情
     * @param id 管理员id
     * @return SystemAdmin
     */
    @Override
    public MerchantAdmin getDetail(Integer id) {
        MerchantAdmin merchantAdmin = getById(id);
        if (ObjectUtil.isNull(merchantAdmin) || merchantAdmin.getIsDel()) {
            throw new HhException("管理员不存在");
        }
        return merchantAdmin;
    }

    @Override
    public Boolean updateStatus(Integer id, Boolean status) {
        MerchantAdmin user = SecurityUtil.getMerLoginUserVo().getUser();
        MerchantAdmin merchantAdmin = getDetail(id);
        if (merchantAdmin.getStatus().equals(status)) {
            return true;
        }
        if(!user.getMerId().equals(merchantAdmin.getMerId())){
            throw new HhException("商户异常，修改失败");
        }
        merchantAdmin.setStatus(status);
        return updateById(merchantAdmin);
    }

    @Override
    public Boolean updateIsSms(Integer id) {
        MerchantAdmin merchantAdmin = getDetail(id);
        if (StrUtil.isBlank(merchantAdmin.getPhone())) {
            throw new HhException("请先为管理员添加手机号!");
        }
        merchantAdmin.setIsSms(!merchantAdmin.getIsSms());
        return updateById(merchantAdmin);
    }

    @Override
    public Boolean deleteAdminUserById(Integer id) {
        MerchantAdmin user = SecurityUtil.getMerLoginUserVo().getUser();
        MerchantAdmin merchantAdmin = getById(id);
        if(!user.getMerId().equals(merchantAdmin.getMerId())){
            throw new HhException("商户异常，删除失败！");
        }
        return removeById(id);
    }

    /**
     * 校验账号唯一性（管理员更新时）
     * @param id 管理员id
     * @param account 管理员账号
     */
    private void verifyAccount(Integer id, String account) {
        LambdaQueryWrapper<MerchantAdmin> lqw = Wrappers.lambdaQuery();
        lqw.ne(MerchantAdmin::getId, id);
        lqw.eq(MerchantAdmin::getAccount, account);
        MerchantAdmin merchantAdmin = dao.selectOne(lqw);
        if (ObjectUtil.isNotNull(merchantAdmin)) {
            throw new HhException("账号已存在");
        }
    }

    /**
     * 管理员名称唯一校验
     * @param account 管理员账号
     * @return Integer
     */
    private Integer checkAccount(String account) {
        LambdaQueryWrapper<MerchantAdmin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(MerchantAdmin::getAccount, account);
        return dao.selectCount(lambdaQueryWrapper);

    }
}
